package net.jsoft.pms.web.mysql.task;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.jsoft.platform.core.util.platform.PlatformUtils;
import net.jsoft.platform.core.web.BaseController;
import net.jsoft.platform.security.entity.user.SysRole;
import net.jsoft.platform.security.entity.user.SysUser;
import net.jsoft.platform.security.repository.UserRepository;
import net.jsoft.pms.entity.dept.Dept;
import net.jsoft.pms.entity.plan.Plan;
import net.jsoft.pms.entity.problem.ProblemTask;
import net.jsoft.pms.repository.task.TaskRepository;
import net.jsoft.pms.service.mysql.problem.IProblemService;
import net.jsoft.pms.web.mysql.versionplan.VPController;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 计划管理控制器
 *
 * @author John
 * @Date 2017-08-03 15:51:51
 */
@Controller
@RequestMapping("/task")
public class TaskController extends BaseController
{

    private String PREFIX = "/pms/mysql/task/";

    @Autowired
    private TaskRepository repository;

    @Autowired
    private UserRepository userRepository;

    @Resource(name = "problemServiceImpl")
    IProblemService service;

    @Autowired
    private VPController vpController;

    @Resource(name = "mysqlJdbcTemplate")
    private JdbcTemplate template;

    private NumberFormat numberFormat = NumberFormat.getInstance();

    //
    //    @Resource(name = "planServiceImpl")
    //    private IPlanService service;
    //
    //    @Resource(name = "problemsServiceImpl")
    //    IProblemsService s;
    /**
     * 跳转到计划管理首页
     */
    @RequestMapping("/list")
    public String index(Model modle)
    {
        SysUser user = this.getUser();
        String leaderFlag = null;
        String groupLeaderFlag = null;
        for (SysRole r : user.getSysRoles())
        {
            if (r.getId() == 3)
            {
                leaderFlag = "1";
            }
            if (r.getId() == 4)
            {
                groupLeaderFlag = "1";
            }

        }
        if ("1".equals(leaderFlag))
        {

        }
        else if ("1".equals(groupLeaderFlag))
        {
            modle.addAttribute("dept", user.getDept().getId());
        }
        else
        {
            modle.addAttribute("dept", user.getDept().getId());
            modle.addAttribute("myself", user.getId());
        }

        modle.addAttribute("vps", vpController.getAllVPData());
        return PREFIX + "list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject listData(int pageSize, int pageNumber, final String sszb, final String beginDate, final String endDate, final String optUser, final String zt) throws ParseException
    {
        List<Map<String, Object>> plans = new ArrayList<Map<String, Object>>();
        int result = 0;
        try
        {
            List<Object> params = new ArrayList<Object>();

            String sql = "select GROUP_CONCAT( distinct CAST( y.ywfwqdId AS CHAR)  SEPARATOR ',') ywfwqd ,GROUP_CONCAT(distinct j.qdbh SEPARATOR ',') qdbh  , p.id,p.name,u.fullName,p.earlyStart,p.earlyFinish,p.source,p.lateStart,p.lateFinish,"
                    + "p.earlyVersion,p.lateVersion,p.notes,p.problemId "
                    + "from t_dzswj_plan p left join t_security_user u on p.optPerson = u.id  left JOIN t_dzswj_plan_ywfwqd y on p.id = y.taskId left join t_dzswj_plan_jcqd j on p.id = j.taskId where 1=1 ";

            if (StringUtils.isNotEmpty(sszb))
            {
                sql += " and p.dept = ? ";
                params.add(sszb);
            }
            if (StringUtils.isNotEmpty(optUser))
            {
                sql += " and p.optPerson = ? ";
                params.add(optUser);
            }
            if (StringUtils.isNotEmpty(zt))
            {
                if ("1".endsWith(zt))
                {
                    sql += "  and p.lateFinish is null   ";
                }
                else
                {
                    sql += "  and p.lateFinish is not null   ";
                }

            }
            if (StringUtils.isNotEmpty(beginDate) && StringUtils.isNotEmpty(endDate))
            {

                sql += "and ((earlyStart between ? and ? ) or( earlyFinish  between ? and ?  )) ";
                params.add(beginDate);
                params.add(endDate);
                params.add(beginDate);
                params.add(endDate);
            }

            sql += " group by p.id,p.name,u.fullName,p.earlyStart,p.earlyFinish,p.source,p.lateStart,p.lateFinish, " + " p.earlyVersion,p.lateVersion,p.notes,p.problemId  order by id desc ";

            String limited = " limit ?,? ";

            String countSql = "select count(1) from (" + sql + ") cc";
            result = template.queryForObject(countSql, params.toArray(), Integer.class);

            params.add((pageNumber - 1) * pageSize);
            params.add(pageSize);

            List<Map<String, Object>> list = template.queryForList(sql + limited, params.toArray());
            plans = new ArrayList<Map<String, Object>>();
            Map<String, Object> t = null;

            for (Map<String, Object> p : list)
            {
                t = new HashMap<String, Object>();
                t.put("id", p.get("id"));
                t.put("name", p.get("name"));
                t.put("resource", p.get("fullName"));
                t.put("earlyStart", p.get("earlyStart") != null ? PlatformUtils.formateDate((Date) p.get("earlyStart"), "yyyyMMdd") : "");
                t.put("earlyFinish", p.get("earlyFinish") != null ? PlatformUtils.formateDate((Date) p.get("earlyFinish"), "yyyyMMdd") : "");
                t.put("source", p.get("source"));
                t.put("lateStart", p.get("lateStart") != null ? PlatformUtils.formateDate((Date) p.get("lateStart"), "yyyyMMdd") : "");
                t.put("lateFinish", p.get("lateFinish") != null ? PlatformUtils.formateDate((Date) p.get("lateFinish"), "yyyyMMdd") : "");
                t.put("earlyVersion", p.get("earlyVersion") == null ? "" : p.get("earlyVersion"));
                t.put("lateVersion", p.get("lateVersion") == null ? "" : p.get("lateVersion"));
                t.put("notes", p.get("notes"));
                t.put("problemsId", p.get("problemId") != null ? p.get("problemId") : "");
                t.put("ywfwqd", p.get("ywfwqd") != null ? p.get("ywfwqd") : "");
                t.put("qdbh", p.get("qdbh") != null ? p.get("qdbh") : "");
                //                byte[] ywfwqdBlob = (byte[]) p.get("ywfwqd");
                //                String ywfwqd = "";
                //                if (ywfwqdBlob != null)
                //                {
                //                    ywfwqd = new String(ywfwqdBlob);
                //                }
                //                t.put("ywfwqd", ywfwqd);

                plans.add(t);

            }
        }
        catch (DataAccessException e)
        {
            e.printStackTrace();
        }

        JSONObject json = new JSONObject();
        json.put("rows", plans); //这里的 rows 和total 的key 是固定的 
        json.put("total", result);
        return json;
    }

    @RequestMapping("/add")
    public String add()
    {
        return PREFIX + "add";
    }

    @RequestMapping("/addSave")
    @ResponseBody
    public String addSave(Plan plan, long sszb, long optUser, String earlyStartStr, String earlyFinishStr, String lateStartStr, String lateFinishStr, String versionDateStr) throws ParseException
    {
        Dept dept = userRepository.findDept(sszb);
        SysUser user = userRepository.findOne(optUser);
        plan.setDept(dept);
        plan.setOptPerson(user);

        if (StringUtils.isNotEmpty(earlyStartStr))
        {
            plan.setEarlyStart(PlatformUtils.getdate(earlyStartStr));
        }
        if (StringUtils.isNotEmpty(earlyFinishStr))
        {
            plan.setEarlyFinish(PlatformUtils.getdate(earlyFinishStr));
        }
        if (StringUtils.isNotEmpty(lateStartStr))
        {
            plan.setLateStart(PlatformUtils.getdate(lateStartStr));
        }
        if (StringUtils.isNotEmpty(lateFinishStr))
        {
            plan.setLateFinish(PlatformUtils.getdate(lateFinishStr));
        }
        if (StringUtils.isNotEmpty(versionDateStr))
        {
            plan.setVersionDate(PlatformUtils.getdate(versionDateStr));
        }
        if (plan.getProblem() != null && StringUtils.isNotEmpty(plan.getProblem().getId().trim()))
        {
            ProblemTask problem = service.findOne(plan.getProblem().getId().trim());
            plan.setProblem(problem);
        }

        plan.setCreateDate(new Date());
        repository.save(plan);
        return "ok";
    }

    @RequestMapping("/edit")
    public String edit(long id, Model model, String type)
    {
        Plan task = repository.findOne(id);
        model.addAttribute("task", task);
        model.addAttribute("type", type);
        model.addAttribute("deptId", task.getDept().getId());
        return PREFIX + "edit";
    }

    @RequestMapping("/editSave")
    @ResponseBody
    public String editSave(Plan plan, long sszb, long optUser, String earlyStartStr, String earlyFinishStr, String lateStartStr, String lateFinishStr, String versionDateStr) throws ParseException
    {
        Dept dept = userRepository.findDept(sszb);
        SysUser user = userRepository.findOne(optUser);
        plan.setDept(dept);
        plan.setOptPerson(user);

        if (StringUtils.isNotEmpty(earlyStartStr))
        {
            plan.setEarlyStart(PlatformUtils.getdate(earlyStartStr));
        }
        if (StringUtils.isNotEmpty(earlyFinishStr))
        {
            plan.setEarlyFinish(PlatformUtils.getdate(earlyFinishStr));
        }
        if (StringUtils.isNotEmpty(lateStartStr))
        {
            plan.setLateStart(PlatformUtils.getdate(lateStartStr));
        }
        if (StringUtils.isNotEmpty(lateFinishStr))
        {
            plan.setLateFinish(PlatformUtils.getdate(lateFinishStr));
        }
        if (StringUtils.isNotEmpty(versionDateStr))
        {
            plan.setVersionDate(PlatformUtils.getdate(versionDateStr));
        }
        if (plan.getProblem() != null && StringUtils.isNoneEmpty(plan.getProblem().getId()))
        {
            ProblemTask problem = service.findOne(plan.getProblem().getId());
            plan.setProblem(problem);
        }

        plan.setCreateDate(new Date());
        repository.save(plan);
        return "ok";
    }

    @RequestMapping("/view")
    public String view(long id, Model model)
    {
        Plan task = repository.findOne(id);
        model.addAttribute("task", task);
        model.addAttribute("deptId", task.getDept().getId());
        String sql = " select  y.qyfwyfwid ,y.fwljms from t_dzswj_ywfwqdb y left join  t_dzswj_plan_ywfwqd py on y.id= py.ywfwqdId where py.taskId   =  ?";
        List<Map<String, Object>> ywfwqd = this.getTemplate().queryForList(sql, id);
        model.addAttribute("ywfwqd", ywfwqd);
        sql = " select qdbh from  t_dzswj_plan_jcqd where taskId = ?";
        List<Map<String, Object>> fbqd = this.getTemplate().queryForList(sql, id);
        model.addAttribute("fbqd", fbqd);
        return PREFIX + "view";
    }

    @RequestMapping("/deskTopPage")
    public String deskTopPage()
    {
        return PREFIX + "deskTop";
    }

    @RequestMapping("/taskPage")
    public String taskPage()
    {
        return PREFIX + "taskPage";
    }

    @RequestMapping("/queryTask")
    public String queryTask(String user, String ywfwqdId, Model model)
    {
        List<Plan> list = null;
        if (StringUtils.isNotEmpty(user))
        {
            list = repository.queryPlan(user);
        }
        else
        {
            list = repository.findAllPlan();
        }

        model.addAttribute("ywfwqdId", ywfwqdId);
        model.addAttribute("list", list);
        return PREFIX + "queryTask";
    }

    @RequestMapping("/deskTopData")
    @ResponseBody
    public Map<String, Object> deskTopDataPage(String date) throws ParseException
    {
        Map<String, Object> resp = new HashMap<String, Object>();

        StringBuffer info = new StringBuffer();
        try
        {
            List<Plan> allTasks = repository.findAllPlan();

            List<Plan> allTaskFinished = repository.findAllFinishedPlan();
            List<Plan> allTaskUnFinished = repository.findAllUnFinishedPlan();
            //            resp.put("allTaskFinished", allTaskFinished);
            //            resp.put("allTaskUnFinished", allTaskUnFinished);
            //            resp.put("allTasks", allTasks);
            //
            //            resp.put("allTasksByGroup", groupTasks(allTaskFinished));
            //            resp.put("allTaskFinishedByGroup", groupTasks(allTaskFinished));
            //            resp.put("allTaskUnFinishedByGroup", groupTasks(allTaskUnFinished));

            Map<String, Date> days = PlatformUtils.getDays(PlatformUtils.getdate(date));

            Map<String, String> daystr = new HashMap<String, String>();
            for (String k : days.keySet())
            {
                daystr.put(k, PlatformUtils.getdate(days.get(k)).replaceAll("-", ""));
            }

            resp.putAll(daystr);
            // 上周任务
            List<Plan> lastWeek = repository.getPeriodTasks(days.get("lastWeekMonday"), days.get("lastWeekSunday"));
            List<Plan> lastWeekFinished = repository.getPeriodFinishedTasks(days.get("lastWeekMonday"), days.get("lastWeekSunday"));
            List<Plan> lastWeekUnFinished = repository.getPeriodUnFinishedTasks(days.get("lastWeekMonday"), days.get("lastWeekSunday"));
            //            resp.put("lastWeek", lastWeek);
            //            resp.put("lastWeekFinished", lastWeekFinished);
            //            resp.put("lastWeekUnFinished", lastWeekUnFinished);
            //
            Map<String, List<Plan>> lastWeekByGroup = groupTasks(lastWeek);
            //                        resp.put("lastWeekByGroup", groupTasks(lastWeek));
            //            resp.put("lastWeekFinishedByGroup", groupTasks(lastWeekFinished));
            //            resp.put("lastWeekUnFinishedByGroup", groupTasks(lastWeekUnFinished));

            List<Plan> lastWeekPlaned = repository.getWeekPlaned(days.get("lastWeekMonday"), days.get("lastWeekSunday"));
            List<Plan> lastWeekUnPlaned = repository.getWeekUnPlaned(days.get("lastWeekMonday"), days.get("lastWeekSunday"));
            //            resp.put("lastWeekPlaned", lastWeekPlaned);
            //            resp.put("lastWeekUnPlaned", lastWeekUnPlaned);
            //            resp.put("lastWeekPlanedByGroup", groupTasks(lastWeekPlaned));
            //            resp.put("lastWeekUnPlanedByGroup", groupTasks(lastWeekUnPlaned));

            // 本周任务
            List<Plan> thisWeek = repository.getPeriodTasks(days.get("thisWeekMonday"), days.get("thisWeekSunday"));
            List<Plan> thisWeekFinished = repository.getPeriodFinishedTasks(days.get("thisWeekMonday"), days.get("thisWeekSunday"));
            List<Plan> thisWeekUnFinished = repository.getPeriodUnFinishedTasks(days.get("thisWeekMonday"), days.get("thisWeekSunday"));
            //            resp.put("thisWeek", thisWeek);
            //            resp.put("thisWeekFinished", thisWeekFinished);
            //            resp.put("thisWeekUnFinished", thisWeekUnFinished);
            Map<String, List<Plan>> thisWeekByGroup = groupTasks(thisWeek);
            //            resp.put("thisWeekByGroup", groupTasks(thisWeek));
            //            resp.put("thisWeekFinishedByGroup", groupTasks(thisWeekFinished));
            //            resp.put("thisWeekUnFinishedByGroup", groupTasks(thisWeekUnFinished));

            List<Plan> thisWeekPlaned = repository.getWeekPlaned(days.get("thisWeekMonday"), days.get("thisWeekSunday"));
            List<Plan> thisWeekUnPlaned = repository.getWeekUnPlaned(days.get("thisWeekMonday"), days.get("thisWeekSunday"));

            //            resp.put("thisWeekPlaned", thisWeekPlaned);
            //            resp.put("thisWeekUnPlaned", thisWeekUnPlaned);
            //            resp.put("thisWeekPlanedByGroup", groupTasks(thisWeekPlaned));
            //            resp.put("thisWeekUnPlanedByGroup", groupTasks(thisWeekUnPlaned));

            // 下周任务
            List<Plan> nextWeek = repository.getPeriodTasks(days.get("nextWeekMonday"), days.get("nextWeekSunday"));
            List<Plan> nextWeekFinished = repository.getPeriodFinishedTasks(days.get("nextWeekMonday"), days.get("nextWeekSunday"));
            List<Plan> nextWeekUnFinished = repository.getPeriodUnFinishedTasks(days.get("nextWeekMonday"), days.get("nextWeekSunday"));
            //            resp.put("nextWeek", nextWeek);
            //            resp.put("nextWeekFinished", nextWeekFinished);
            //            resp.put("nextWeekUnFinished", nextWeekUnFinished);
            Map<String, List<Plan>> nextWeekByGroup = groupTasks(nextWeek);
            //            resp.put("nextWeekByGroup", groupTasks(nextWeek));
            //            resp.put("nextWeekFinishedByGroup", groupTasks(nextWeekFinished));
            //            resp.put("nextWeekUnFinishedByGroup", groupTasks(nextWeekUnFinished));

            //        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();

            info.append("计划统计：<br/>");
            numberFormat.setMaximumFractionDigits(2);
            info.append("计划数：共").append(allTasks.size()).append("个，完成").append(allTaskFinished.size()).append("个，未完成").append(allTaskUnFinished.size()).append("个，完成率为：")
                    .append(numberFormat.format((float) allTaskFinished.size() / (float) allTasks.size() * 100)).append("%<br/>");

            info.append("上周(").append(daystr.get("lastWeekMonday")).append("-").append(daystr.get("lastWeekSunday")).append(")计划数：<a href='javascript:openTask(\"lastWeek\")' >共")
                    .append(lastWeek.size()).append("个</a>，完成").append(lastWeekFinished.size()).append("个，<a href='javascript:openTask(\"lastWeekUnFinished\")' >剩余").append(lastWeekUnFinished.size())
                    .append("个</a>，完成率为：").append(numberFormat.format((float) lastWeekFinished.size() / (float) lastWeek.size() * 100)).append("%，计划内任务").append(lastWeekPlaned.size())
                    .append("个,临时性计划任务").append(lastWeekUnPlaned.size()).append("个，计划率为").append(numberFormat.format((float) lastWeekPlaned.size() / (float) lastWeek.size() * 100)).append("%<br/>");

            info.append("本周(").append(daystr.get("thisWeekMonday")).append("-").append(daystr.get("thisWeekSunday")).append(")计划数：<a href='javascript:openTask(\"thisWeek\")' >共")
                    .append(thisWeek.size()).append("个</a>，完成").append(thisWeekFinished.size()).append("个，<a href='javascript:openTask(\"thisWeekUnFinished\")' >剩余").append(thisWeekUnFinished.size())
                    .append("个</a>，完成率为：").append(numberFormat.format((float) thisWeekFinished.size() / (float) thisWeek.size() * 100)).append("%，计划内任务").append(thisWeekPlaned.size())
                    .append("个,临时性计划任务").append(thisWeekUnPlaned.size()).append("个，计划率为").append(numberFormat.format((float) thisWeekPlaned.size() / (float) thisWeek.size() * 100)).append("%<br/>");

            info.append("下周(").append(daystr.get("nextWeekMonday")).append("-").append(daystr.get("nextWeekSunday")).append(")计划数：<a href='javascript:openTask(\"nextWeek\")' >共")
                    .append(nextWeek.size()).append("个</a>，完成").append(nextWeekFinished.size()).append("个，<a href='javascript:openTask(\"nextWeekUnFinished\")' >剩余").append(nextWeekUnFinished.size())
                    .append("个</a>，完成率为：").append(numberFormat.format((float) nextWeekFinished.size() / (float) nextWeek.size() * 100)).append("%<br/>");

            info.append("<script>");
            info.append("var lastWeekByGroupData = ").append(JSONObject.fromObject(lastWeekByGroup).toString()).append(";");
            info.append("var thisWeekByGroupData = ").append(JSONObject.fromObject(thisWeekByGroup).toString()).append(";");
            info.append("var nextWeekByGroupData = ").append(JSONObject.fromObject(nextWeekByGroup).toString()).append(";");
            info.append("var lastWeekUnFinishedByGroupData = ").append(JSONObject.fromObject(groupTasks(lastWeekUnFinished)).toString()).append(";");
            info.append("var thisWeekUnFinishedByGroupData = ").append(JSONObject.fromObject(groupTasks(thisWeekUnFinished)).toString()).append(";");
            info.append("var nextWeekUnFinishedByGroupData = ").append(JSONObject.fromObject(groupTasks(nextWeekUnFinished)).toString()).append(";");
            info.append("function openTask(type) {");
            info.append("var tempTask;");
            info.append("var title;");
            info.append("if (type == \"lastWeek\") {");
            info.append("    tempTask = lastWeekByGroupData;");
            info.append("    title = \"上周任务\";");
            info.append(" }else if (type == \"thisWeek\") {");
            info.append("    title = \"本周任务\";");
            info.append("     tempTask = thisWeekByGroupData;");
            info.append(" } else if (type == \"nextWeek\") {");
            info.append("     title = \"下周任务\";");
            info.append("     tempTask = nextWeekByGroupData;");
            info.append(" } else if (type == \"lastWeekUnFinished\") {");
            info.append("    title = \"上周未完成任务\";");
            info.append("     tempTask = lastWeekUnFinishedByGroupData;");
            info.append(" }");

            info.append("   else if (type == \"thisWeekUnFinished\") {");
            info.append("     title = \"本周未完成任务\";");
            info.append("      tempTask = thisWeekUnFinishedByGroupData;");
            info.append("  }");

            info.append("   else if (type == \"nextWeekUnFinished\") {");
            info.append("      title = \"下周未完成任务\";");
            info.append("      tempTask = nextWeekUnFinishedByGroupData;");
            info.append("   }");

            info.append("layer.open({");
            info.append("type : 2,");
            info.append("title : title,");
            info.append("shadeClose : true,");
            info.append("shade : false,");
            info.append("maxmin : true,");
            info.append("offset: '30px',");
            info.append("area : [ '893px', '500px' ],");
            info.append("content : '/task/taskPage',");
            info.append("success : function(layero, index) {");
            info.append("var iframeWin = window[layero.find('iframe')[0]['name']];");
            info.append("var flag = iframeWin.setTable(tempTask);");
            info.append("}");
            info.append("});");
            info.append("}");
            info.append("</script>");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        resp.put("info", info.toString());
        return resp;

    }

    private Map<String, List<Plan>> groupTasks(List<Plan> tasks)
    {
        Map<String, List<Plan>> map = new HashMap<String, List<Plan>>();
        Map<String, List<Plan>> returnMap = new HashMap<String, List<Plan>>();
        for (Plan p : tasks)
        {
            if (map.containsKey(p.getDept().getName()))
            {
                List<Plan> newList = map.get(p.getDept().getName());
                newList.add(p);
                map.put(p.getDept().getName(), newList);
            }
            else
            {
                List<Plan> newList = new ArrayList<Plan>();
                newList.add(p);
                map.put(p.getDept().getName(), newList);
            }
        }
        returnMap.put("tasks2", map.get("局端报税组") != null ? map.get("局端报税组") : new ArrayList<Plan>());
        returnMap.put("tasks1", map.get("局端办税组") != null ? map.get("局端办税组") : new ArrayList<Plan>());
        returnMap.put("tasks3", map.get("局端信息组") != null ? map.get("局端信息组") : new ArrayList<Plan>());
        returnMap.put("tasks4", map.get("总体组") != null ? map.get("总体组") : new ArrayList<Plan>());
        return returnMap;
    }

    @RequestMapping("/problemNoTaskRisk")
    @ResponseBody
    public String problemNoTaskRisk()
    {
        StringBuffer info = new StringBuffer();
        List<ProblemTask> list = service.findNoTaskProblems();
        info.append("未安排计划的问题管理平台数据<a href= 'javascript:openProblemRisk()'>共计").append(list.size()).append("个</a>");
        info.append("<script>");
        info.append("function openProblemRisk(){");
        info.append("var tempPro = ").append(JSONArray.fromObject(list).toString()).append(";");
        info.append("var title ='未安排计划的问题管理平台的问题';");
        info.append("layer.open({");
        info.append("type : 2,");
        info.append("title : title,");
        info.append("shadeClose : true,");
        info.append("shade : false,");
        info.append("maxmin : true,");
        info.append("area : [ '893px', '600px' ],");
        info.append("maxmin : true,");
        info.append("content : '/problem/problemsPage',");
        info.append("success : function(layero, index) {");
        info.append("var iframeWin = window[layero.find('iframe')[0]['name']];");
        info.append("var flag = iframeWin.setTable(tempPro);");
        info.append("}");
        info.append("});");
        info.append("}");

        info.append("</script>");
        return info.toString();
    }

    @RequestMapping("/delayTaskRisk")
    @ResponseBody
    public String delayTaskRisk(String date) throws Exception
    {
        StringBuffer info = new StringBuffer();

        List<Plan> list = repository.delayTaskRisk(new Date());
        String str = JSONObject.fromObject(groupTasks(list)).toString();
        info.append("延期任务<a href= 'javascript:delayTaskRisk()'>共计").append(list.size()).append("个</a>");
        info.append("<script>");
        info.append("function delayTaskRisk(){");
        info.append("var delayTask = ").append(str).append(";");
        info.append("var title ='延期任务';");
        info.append("layer.open({");
        info.append("type : 2,");
        info.append("title : title,");
        info.append("shadeClose : true,");
        info.append("shade : false,");
        info.append("maxmin : true,");
        info.append("offset: '30px',");
        info.append("area : [ '893px', '600px' ],");
        info.append("maxmin : true,");
        info.append("content : '/task/taskPage',");
        info.append("success : function(layero, index) {");
        info.append("var iframeWin = window[layero.find('iframe')[0]['name']];");
        info.append("var flag = iframeWin.setTable(delayTask);");
        info.append("}");
        info.append("});");
        info.append("}");
        info.append("</script>");
        return info.toString();
    }

    @RequestMapping("/noVPRisk")
    @ResponseBody
    public String noVPRisk(String date) throws Exception
    {
        StringBuffer info = new StringBuffer();

        List<Plan> list = repository.noVP();
        String str = JSONObject.fromObject(groupTasks(list)).toString();
        info.append("无版本计划风险：应该安排版本计划且未安排的任务<a href= 'javascript:noVP()'>共计").append(list.size()).append("个</a>");
        info.append("<script>");
        info.append("function noVP(){");
        info.append("var nvpTask = ").append(str).append(";");
        info.append("var title ='无版本计划风险';");
        info.append("layer.open({");
        info.append("type : 2,");
        info.append("title : title,");
        info.append("shadeClose : true,");
        info.append("shade : false,");
        info.append("maxmin : true,");
        info.append("offset: '30px',");
        info.append("area : [ '893px', '600px' ],");
        info.append("maxmin : true,");
        info.append("content : '/task/taskPage',");
        info.append("success : function(layero, index) {");
        info.append("var iframeWin = window[layero.find('iframe')[0]['name']];");
        info.append("var flag = iframeWin.setTable(nvpTask);");
        info.append("}");
        info.append("});");
        info.append("}");
        info.append("</script>");
        return info.toString();
    }

    @RequestMapping("/workload")
    @ResponseBody
    public String workload(String date) throws Exception
    {
        StringBuffer info = new StringBuffer();
        try
        {
            Map<String, Date> days = PlatformUtils.getDays(PlatformUtils.getdate(date));
            List<Plan> tasks = repository.getPeriodFinishedTasks(days.get("lastWeekMonday"), days.get("nextWeekSunday"));
            List<SysUser> users = userRepository.findAllOrderByDept();

            List<String> dateStrs = PlatformUtils.getAllDate(days.get("lastWeekMonday"), days.get("nextWeekSunday"));

            Map<SysUser, Map<String, Integer>> workLoad = initResourceMap(users, days.get("lastWeekMonday"), days.get("nextWeekSunday"));

            for (Plan p : tasks)
            {
                Map<String, Integer> temp = workLoad.get(p.getOptPerson());
                if (temp != null)
                {
                    List<String> list = PlatformUtils.getAllDate(p.getEarlyStart(), p.getEarlyFinish());
                    for (String l : list)
                    {
                        if (temp.get(l) != null)
                        {
                            temp.put(l, temp.get(l) + 1);
                        }

                    }
                    workLoad.put(p.getOptPerson(), temp);
                }

            }

            info = new StringBuffer();
            info.append("<table class='table table-bordered  table-striped table-hover'>");
            info.append("<thead>");
            info.append("  <tr>");
            info.append("    <th >姓名</th>");
            for (String s : dateStrs)
            {
                s = s != null ? s.replaceAll("-", "") : "";
                info.append("    <th>").append(s.substring(4)).append("</th>");
            }
            info.append("   </tr>");
            info.append(" </thead>");
            info.append("<tbody>");
            for (SysUser s : workLoad.keySet())
            {
                info.append("  <tr>");
                info.append("    <td>").append(s.getFullName()).append("</td>");
                Map<String, Integer> work = workLoad.get(s);
                int i = 0;
                for (String w : work.keySet())
                {
                    if (i > 6 && i <= 13)
                    {
                        info.append("    <td  style = 'background-color:#00ff00' >").append(work.get(w)).append("</td>");

                    }
                    else
                    {
                        info.append("    <td  >").append(work.get(w)).append("</td>");
                    }
                    i++;

                }
                info.append("   </tr>");
            }
            info.append(" </tbody>");
            info.append("</table>");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return info.toString();
    }

    @RequestMapping("/delayVPRisk")
    @ResponseBody
    public String delayVPRisk(String date) throws Exception
    {
        StringBuffer info = new StringBuffer();

        Map<String, Object> map = vpController.getNowVersions(date);
        List<Plan> list = repository.delayVPRisk(map.get("nowVersion") + "");
        String str = JSONObject.fromObject(groupTasks(list)).toString();
        info.append("延期版本计划风险：延期且未出厂的任务<a href= 'javascript:delayVP()'>共计").append(list.size()).append("个</a>");
        info.append("<script>");
        info.append("function delayVP(){");
        info.append("var delayVPTask = ").append(str).append(";");
        info.append("var title ='无版本计划风险';");
        info.append("layer.open({");
        info.append("type : 2,");
        info.append("title : title,");
        info.append("shadeClose : true,");
        info.append("shade : false,");
        info.append("maxmin : true,");
        info.append("offset: '30px',");
        info.append("area : [ '893px', '600px' ],");
        info.append("maxmin : true,");
        info.append("content : '/task/taskPage',");
        info.append("success : function(layero, index) {");
        info.append("var iframeWin = window[layero.find('iframe')[0]['name']];");
        info.append("var flag = iframeWin.setTable(delayVPTask);");
        info.append("}");
        info.append("});");
        info.append("}");
        info.append("</script>");
        return info.toString();
    }

    /**
    * 初始化人员列表
    * 
    * @param rc
    * @param lastWeekMonday
    * @param nextWeekSunday
    * @return
     * @throws ParseException 
    */
    private Map<SysUser, Map<String, Integer>> initResourceMap(List<SysUser> users, Date lastWeekMonday, Date nextWeekSunday)
    {
        Map<SysUser, Map<String, Integer>> map = new TreeMap<SysUser, Map<String, Integer>>(new Comparator<SysUser>()
        {
            /* 
            * int compare(Object o1, Object o2) 返回一个基本类型的整型， 
            * 返回负数表示：o1 小于o2， 
            * 返回0 表示：o1和o2相等， 
             * 返回正数表示：o1大于o2。 
             */
            @Override
            public int compare(SysUser o1, SysUser o2)
            {
                if (o1.getDept().getId() == o2.getDept().getId())
                {
                    return (int) (o2.getFullName().hashCode() - o1.getFullName().hashCode());
                }
                return (int) (o1.getDept().getId() - o2.getDept().getId());
            }
        });

        //        Iterator<net.sf.mpxj.Resource> iterator = rc.iterator();
        //        while (iterator.hasNext())
        List<String> userRoles = null;
        for (SysUser u : users)
        {
            userRoles = new ArrayList<String>();
            for (SysRole r : u.getSysRoles())
            {
                userRoles.add(r.getName());
            }
            if (userRoles.contains("UNWORKLOAD"))
            {
                continue;
            }

            Map<String, Integer> temp = new TreeMap<String, Integer>();
            List<String> list = PlatformUtils.getAllDate(lastWeekMonday, nextWeekSunday);
            for (String l : list)
            {
                temp.put(l, 0);
            }
            map.put(u, temp);
        }

        return map;
    }

    //
    //    /**
    //     * 跳转到计划管理首页
    //     */
    //    @RequestMapping("/topdesk")
    //    @ResponseBody
    //    public Map<String, Object> topdesk()
    //    {
    //        Map<String, Object> resp = new HashMap<String, Object>();
    //        // 获取所有工作计划
    //        List<PlanTaskInfo> tasks = null;
    //        if ("DB".equals(type))
    //        {
    //            tasks = service.getAllTasksByDB();
    //        }
    //        else
    //        {
    //            tasks = (List<PlanTaskInfo>) service.getAllTasks().get("planTasks");
    //        }
    //
    //        Map<String, List<PlanTaskInfo>> tempMap = service.groupbyFinishFlag(tasks);
    //        resp.put("allTaskFinished", tempMap.get("finished"));
    //        resp.put("allTaskUnFinished", tempMap.get("unfinished"));
    //        resp.put("allTasks", tasks);
    //        resp.put("allTasksByGroup", service.groupTasks(tasks));
    //        resp.put("allTaskFinishedByGroup", service.groupTasks(tempMap.get("finished")));
    //        resp.put("allTaskUnFinishedByGroup", service.groupTasks(tempMap.get("unfinished")));
    //
    //        Map<String, Date> days = service.getDays(null);
    //        Map<String, String> daystr = new HashMap<String, String>();
    //        for (String k : days.keySet())
    //        {
    //            daystr.put(k, sdf.format(days.get(k)));
    //        }
    //
    //        resp.putAll(daystr);
    //        // 上周任务
    //        List<PlanTaskInfo> lastWeek = service.getPeriodTasks(tasks, days.get("lastWeekMonday"), days.get("lastWeekSunday"));
    //        resp.put("lastWeek", lastWeek);
    //        tempMap = service.groupbyFinishFlag(lastWeek);
    //        resp.put("lastWeekFinished", tempMap.get("finished"));
    //        resp.put("lastWeekUnFinished", tempMap.get("unfinished"));
    //
    //        resp.put("lastWeekByGroup", service.groupTasks(lastWeek));
    //        resp.put("lastWeekFinishedByGroup", service.groupTasks(tempMap.get("finished")));
    //        resp.put("lastWeekUnFinishedByGroup", service.groupTasks(tempMap.get("unfinished")));
    //
    //        tempMap = service.groupbyPlanType(lastWeek);
    //        resp.put("lastWeekPlaned", tempMap.get("planed"));
    //        resp.put("lastWeekUnPlaned", tempMap.get("unplaned"));
    //        resp.put("lastWeekPlanedByGroup", service.groupTasks(tempMap.get("planed")));
    //        resp.put("lastWeekUnPlanedByGroup", service.groupTasks(tempMap.get("unplaned")));
    //
    //        // 本周任务
    //        List<PlanTaskInfo> thisWeek = service.getPeriodTasks(tasks, days.get("thisWeekMonday"), days.get("thisWeekSunday"));
    //        resp.put("thisWeek", thisWeek);
    //        tempMap = service.groupbyFinishFlag(thisWeek);
    //        resp.put("thisWeekFinished", tempMap.get("finished"));
    //        resp.put("thisWeekUnFinished", tempMap.get("unfinished"));
    //
    //        resp.put("thisWeekByGroup", service.groupTasks(thisWeek));
    //        resp.put("thisWeekFinishedByGroup", service.groupTasks(tempMap.get("finished")));
    //        resp.put("thisWeekUnFinishedByGroup", service.groupTasks(tempMap.get("unfinished")));
    //
    //        tempMap = service.groupbyPlanType(thisWeek);
    //        resp.put("thisWeekPlaned", tempMap.get("planed"));
    //        resp.put("thisWeekUnPlaned", tempMap.get("unplaned"));
    //        resp.put("thisWeekPlanedByGroup", service.groupTasks(tempMap.get("planed")));
    //        resp.put("thisWeekUnPlanedByGroup", service.groupTasks(tempMap.get("unplaned")));
    //
    //        // 下周任务
    //        List<PlanTaskInfo> nextWeek = service.getPeriodTasks(tasks, days.get("nextWeekMonday"), days.get("nextWeekSunday"));
    //        resp.put("nextWeek", nextWeek);
    //        tempMap = service.groupbyFinishFlag(nextWeek);
    //        resp.put("nextWeekFinished", tempMap.get("finished"));
    //        resp.put("nextWeekUnFinished", tempMap.get("unfinished"));
    //
    //        resp.put("nextWeekByGroup", service.groupTasks(nextWeek));
    //        resp.put("nextWeekFinishedByGroup", service.groupTasks(tempMap.get("finished")));
    //        resp.put("nextWeekUnFinishedByGroup", service.groupTasks(tempMap.get("unfinished")));
    //        // 延期任务
    //        Date yearStart = null;
    //        try
    //        {
    //            yearStart = sdf.parse("2017-01-01");
    //        }
    //        catch (ParseException e)
    //        {
    //            e.printStackTrace();
    //        }
    //
    //        List<PlanTaskInfo> dalayTasksTemp = service.getPeriodTasks(tasks, yearStart, days.get("nextWeekMonday"));
    //        List<PlanTaskInfo> dalayTasks = new ArrayList<PlanTaskInfo>();
    //        for (PlanTaskInfo p : dalayTasksTemp)
    //        {
    //            if ("未完成".equals(p.getFinishFlag()) && p.getEarlyFinish().before(days.get("thisWeekMonday")))
    //            {
    //                dalayTasks.add(p);
    //            }
    //        }
    //        resp.put("dalayTasks", dalayTasks);
    //        resp.put("dalayTasksByGroup", service.groupTasks(dalayTasks));
    //        return resp;
    //
    //    }
    //
    //    @RequestMapping(value = "/uploadFile")
    //    public void importFile(HttpServletRequest req, @RequestParam(value = "planFile") MultipartFile file) throws Exception
    //    {
    //        //判断文件是否为空
    //        if (file == null)
    //        {
    //            throw new Exception("文件为空");
    //        }
    //
    //        //获取文件名
    //        String fileName = file.getOriginalFilename();
    //
    //        //进一步判断文件内容是否为空（即判断其大小是否为0或其名称是否为null）
    //        long size = file.getSize();
    //        if (StringUtils.isEmpty(fileName) || size == 0)
    //        {
    //            throw new Exception("文件不能为空！");
    //        }
    //
    //        //批量导入
    //        service.batchImport(file.getInputStream());
    //
    //    }
    //
    //    // 导出excel方法
    //    @SuppressWarnings(
    //    { "resource" })
    //    @RequestMapping("/exportExcel")
    //    public void exportExcel(HttpServletRequest request, HttpServletResponse response)
    //    {
    //        HttpSession session = request.getSession();
    //        session.setAttribute("state", null);
    //        // 生成提示信息，
    //        response.setContentType("application/vnd.ms-excel");
    //        String codedFileName = null;
    //        OutputStream fOut = null;
    //
    //        try
    //        {
    //
    //            NumberFormat numberFormat = NumberFormat.getInstance();
    //            numberFormat.setMaximumFractionDigits(2);
    //
    //            Map<String, Object> map = topdesk();
    //
    //            List<PlanTaskInfo> thisWeek = (List<PlanTaskInfo>) map.get("thisWeek");
    //            List<PlanTaskInfo> thisWeekFinished = (List<PlanTaskInfo>) map.get("thisWeekFinished");
    //            List<PlanTaskInfo> thisWeekUnFinished = (List<PlanTaskInfo>) map.get("thisWeekUnFinished");
    //            List<PlanTaskInfo> nextWeek = (List<PlanTaskInfo>) map.get("nextWeek");
    //            List<PlanTaskInfo> nextWeekFinished = (List<PlanTaskInfo>) map.get("nextWeekFinished");
    //            List<PlanTaskInfo> nextWeekUnFinished = (List<PlanTaskInfo>) map.get("nextWeekUnFinished");
    //            List<PlanTaskInfo> allTasks = (List<PlanTaskInfo>) map.get("allTasks");
    //            List<PlanTaskInfo> allTaskFinished = (List<PlanTaskInfo>) map.get("allTaskFinished");
    //            List<PlanTaskInfo> allTaskUnFinished = (List<PlanTaskInfo>) map.get("allTaskUnFinished");
    //
    //            // 进行转码，使其支持中文文件名
    //            codedFileName = URLEncoder.encode(map.get("thisWeekMonday").toString().replaceAll("-", "") + "-" + map.get("thisWeekSunday").toString().replaceAll("-", "") + "计划完成情况", "UTF-8");
    //            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xlsx");
    //            // 产生工作簿对象
    //            XSSFWorkbook workbook = new XSSFWorkbook();
    //
    //            XSSFCellStyle cellStyle = workbook.createCellStyle();
    //            cellStyle.setWrapText(true);
    //
    //            //计划概要
    //            XSSFSheet sheet0 = workbook.createSheet("计划概要");
    //            XSSFRow row = sheet0.createRow(4);// 创建一行
    //            row.setRowStyle(cellStyle);
    //
    //            row.createCell(2, CellType.STRING).setCellValue("日期");
    //            row.createCell(3, CellType.STRING).setCellValue("计划完成");
    //            row.createCell(4, CellType.STRING).setCellValue("实际完成");
    //            row.createCell(5, CellType.STRING).setCellValue("未完成");
    //            row.createCell(6, CellType.STRING).setCellValue("完成率");
    //
    //            row = sheet0.createRow(5);// 创建一行
    //            row.setRowStyle(cellStyle);
    //            row.createCell(2, CellType.STRING).setCellValue(map.get("thisWeekMonday") + "-" + map.get("thisWeekSunday"));
    //            row.createCell(3, CellType.STRING).setCellValue(thisWeek.size() + "");
    //            row.createCell(4, CellType.STRING).setCellValue(thisWeekFinished.size() + "");
    //            row.createCell(5, CellType.STRING).setCellValue(thisWeekUnFinished.size() + "");
    //            row.createCell(6, CellType.STRING).setCellValue(numberFormat.format((float) thisWeekFinished.size() / (float) thisWeek.size() * 100) + "%");
    //
    //            row = sheet0.createRow(6);// 创建一行
    //            row.setRowStyle(cellStyle);
    //            row.createCell(2, CellType.STRING).setCellValue(map.get("nextWeekMonday") + "-" + map.get("nextWeekSunday"));
    //            row.createCell(3, CellType.STRING).setCellValue(nextWeek.size() + "");
    //            row.createCell(4, CellType.STRING).setCellValue(nextWeekFinished.size() + "");
    //            row.createCell(5, CellType.STRING).setCellValue(nextWeekUnFinished.size() + "");
    //            row.createCell(6, CellType.STRING).setCellValue(numberFormat.format((float) nextWeekFinished.size() / (float) nextWeek.size() * 100) + "%");
    //
    //            row = sheet0.createRow(7);// 创建一行
    //            row.setRowStyle(cellStyle);
    //            row.createCell(2, CellType.STRING).setCellValue("总体计划");
    //            row.createCell(3, CellType.STRING).setCellValue(allTasks.size() + "");
    //            row.createCell(4, CellType.STRING).setCellValue(allTaskFinished.size() + "");
    //            row.createCell(5, CellType.STRING).setCellValue(allTaskUnFinished.size() + "");
    //            row.createCell(6, CellType.STRING).setCellValue(numberFormat.format((float) allTaskFinished.size() / (float) allTasks.size() * 100) + "%");
    //
    //            //本周计划
    //            // 产生工作表对象
    //            XSSFSheet sheet1 = workbook.createSheet("本周计划");
    //            int i = 1;
    //
    //            row = sheet1.createRow(0);// 创建一行
    //            row.setRowStyle(cellStyle);
    //            row.createCell(0, CellType.STRING).setCellValue("计划名称");
    //            row.createCell(1, CellType.STRING).setCellValue("组别");
    //            row.createCell(2, CellType.STRING).setCellValue("处理人员");
    //            row.createCell(3, CellType.STRING).setCellValue("开始时间");
    //            row.createCell(4, CellType.STRING).setCellValue("完成时间");
    //            row.createCell(5, CellType.STRING).setCellValue("问题管理平台编号");
    //            row.createCell(6, CellType.STRING).setCellValue("完成情况");
    //            row.createCell(7, CellType.STRING).setCellValue("备注");
    //
    //            for (PlanTaskInfo p : thisWeek)
    //            {
    //                row = sheet1.createRow(i);// 创建一行
    //                row.setRowStyle(cellStyle);
    //                row.createCell(0, CellType.STRING).setCellValue(p.getName());
    //                row.createCell(1, CellType.STRING).setCellValue(p.getGroupName());
    //                row.createCell(2, CellType.STRING).setCellValue(p.getResourceName());
    //                row.createCell(3, CellType.STRING).setCellValue(sdf.format(p.getEarlyStart()));
    //                row.createCell(4, CellType.STRING).setCellValue(sdf.format(p.getEarlyFinish()));
    //                row.createCell(5, CellType.STRING).setCellValue(p.getProblemsId());
    //                row.createCell(6, CellType.STRING).setCellValue(p.getFinishFlag());
    //                row.createCell(7, CellType.STRING).setCellValue(p.getNotes());
    //                i++;
    //            }
    //
    //            //下周计划
    //
    //            XSSFSheet sheet2 = workbook.createSheet("下周计划");
    //            i = 1;
    //
    //            row = sheet2.createRow(0);// 创建一行
    //            row.setRowStyle(cellStyle);
    //            row.createCell(0, CellType.STRING).setCellValue("计划名称");
    //            row.createCell(1, CellType.STRING).setCellValue("组别");
    //            row.createCell(2, CellType.STRING).setCellValue("处理人员");
    //            row.createCell(3, CellType.STRING).setCellValue("开始时间");
    //            row.createCell(4, CellType.STRING).setCellValue("完成时间");
    //            row.createCell(5, CellType.STRING).setCellValue("问题管理平台编号");
    //            row.createCell(6, CellType.STRING).setCellValue("完成情况");
    //            row.createCell(7, CellType.STRING).setCellValue("备注");
    //
    //            for (PlanTaskInfo p : nextWeek)
    //            {
    //                row = sheet2.createRow(i);// 创建一行
    //                row.setRowStyle(cellStyle);
    //                row.createCell(0, CellType.STRING).setCellValue(p.getName());
    //                row.createCell(1, CellType.STRING).setCellValue(p.getGroupName());
    //                row.createCell(2, CellType.STRING).setCellValue(p.getResourceName());
    //                row.createCell(3, CellType.STRING).setCellValue(sdf.format(p.getEarlyStart()));
    //                row.createCell(4, CellType.STRING).setCellValue(sdf.format(p.getEarlyFinish()));
    //                row.createCell(5, CellType.STRING).setCellValue(p.getProblemsId());
    //                row.createCell(6, CellType.STRING).setCellValue(p.getFinishFlag());
    //                row.createCell(7, CellType.STRING).setCellValue(p.getNotes());
    //                i++;
    //            }
    //
    //            fOut = response.getOutputStream();
    //            workbook.write(fOut);
    //        }
    //        catch (UnsupportedEncodingException e1)
    //        {
    //        }
    //        catch (Exception e)
    //        {
    //        }
    //        finally
    //        {
    //            try
    //            {
    //                if (fOut != null)
    //                {
    //                    fOut.flush();
    //                    fOut.close();
    //                }
    //            }
    //            catch (IOException e)
    //            {
    //            }
    //            session.setAttribute("state", "open");
    //        }
    //    }

}
